#!/usr/bin/env python2
# coding:utf-8

import random

import eventlet
import task


####################################################################################
@task.rtk()
def long_action(number, task_id, progress):
    tries = (progress or 0) + 1
    eventlet.sleep(random.randrange(3))
    if random.randint(1, 10) > 3:
        print "Action %s failed" % number
        raise task.Failure(tries)
    print "Action %s succee after %s tries" % (number, tries)
    return tries
#  
# task.setup_db('sqlite://') 
# # task.setup_db('sqlite:///xx.sqlite') 
#  
# task_ids = []
# for i in xrange(10):
#     task_ids.append(long_action(i))
# 
# 
# while not all(task.is_complete(task_id) for task_id in task_ids):
#     task_id = task.request()
#     if task_id:
#         eventlet.spawn_n(task.run, task_id)
#     eventlet.sleep(0)
# 
# for task_id in task_ids:
#     print task.get(task_id)['attempts']
#    
####################################################################################


class Father(object):
    def __init__(self):
        super(Father, self).__init__()
#         self.value = value
    
    @task.rtk()
    def long_action(self, *args, **kwargs):
        number = args[1]
        task_id = kwargs.pop('task_id')
        progress = kwargs.pop('progress')
        tries = (progress or 0) + 1
        eventlet.sleep(random.randrange(3))
        if random.randint(1, 10) > 3:
            print "Action %s failed" % number
            raise task.Failure(tries)
        print "Action %s succee after %s tries" % (number, tries)
        return tries
    
task.setup_db('sqlite://')

# f_obj = Father()
# 
# task_ids = []
# for i in xrange(10):
#     task_ids.append(f_obj.long_action(i))
# 
# 
# while not all(task.is_complete(task_id) for task_id in task_ids):
#     task_id = task.request()
#     if task_id:
#         eventlet.spawn_n(task.run, task_id)
#     eventlet.sleep(0)
#  
# for task_id in task_ids:
#     print task.get(task_id)['attempts']

@task.rtk()    
def f_test(*args, **kwargs):
    f_obj = Father()
    task_ids = []
    for i in xrange(10):
        task_ids.append(f_obj.long_action(i))
        
    while not all(task.is_complete(task_id) for task_id in task_ids):
        task_id = task.request()
        if task_id:
            eventlet.spawn_n(task.run, task_id)
        eventlet.sleep(0)

task_id = f_test()
print task.is_complete(task_id)
task.run(task_id)
print task.is_complete(task_id)


